package com.cy.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @author tang
 * @data 2021/9/22
 * @apiNode
 * 自定义异常处理
 */
@Component
public class ServiceBlockExectionHandler implements BlockExceptionHandler {
    /**
     * 一旦服务器被限流或降级了,sentinel系统底层提供的拦截器会调用此方法对异常进行处理
     * @param httpServletRequest
     * @param httpServletResponse
     * @param e
     * @throws Exception
     */
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        /**
         * 方案一:  throw e  异常继续抛出
         * 方案二:  对异常内容进行处理(返回给客户端一个可以看得懂的信息)
         * 思考:
         *  1）向客户端输出数据用输出流对象
         *  2）借助HttpServletResponse获取输出流对象
         *  3）当向客户端输出数据时,除了响应业务数据外,还要做什么?
         */
        //设置响应编码
        httpServletResponse.setCharacterEncoding("utf-8");
        //告诉浏览器服务端向他响应的数据类型,以及以什么编码进行显示
        //httpServletResponse.setContentType("text/html;charset=utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //响应业务数据
        PrintWriter out = httpServletResponse.getWriter();
        HashMap<String, Object> map = new HashMap<>();
        map.put("status", 429);
        if (e instanceof DegradeException){  //DegradeException降级异常
            //out.print("<h2>服务暂时不可用</h2>");
            map.put("message", "服务暂时不可用");
        }else {
            //out.print("<h2>访问太频繁，稍等片刻</h2>");
            map.put("message", "访问太频繁，稍等片刻");
        }
        String value = new ObjectMapper().writeValueAsString(map);
        out.print(value);
        out.flush();
    }
}
